package com.ele.web;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        // 设置解析文件时临时存储的位置
        FileItemFactory factory = new DiskFileItemFactory();
        // 设置上传的文件临时存储目录，不设置，采用系统默认的临时目录（c：temp）
        //fileItemFactory.setRepository(new File("d:/dirs"));
        // 让解析工厂 和 解析上传项进行组合
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // 开始从request中解析上传的每一项
            List<FileItem> fileItems = upload.parseRequest(req);
            FileItem fileItem = fileItems.get(0);
            if(!fileItem.isFormField()){
                // 获取上传的文件名
                String filename = fileItem.getName();
                // 获取上传的文件关联的输入流
                InputStream in = fileItem.getInputStream();
                String imgAddr = uploadFile(in, filename);
                // 将上传成功之后的图片在阿里云oss上的地址返给前端
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().write(imgAddr);
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        }


        // 需要获取到上传的文件数据
        // 将文件数据交给阿里云的oss

    }
    /**
     AccessKey ID    LTAI5tNRk4feMNCuR36RUUnY
     AccessKey Secret  MEsij1juoMboQaTKxQt07QVb1uiEAU
     */
    private String uploadFile(InputStream input, String filename){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        DefaultCredentialProvider defaultCredentialProvider =
                CredentialsProviderFactory.newDefaultCredentialProvider("LTAI5tNRk4feMNCuR36RUUnY", "MEsij1juoMboQaTKxQt07QVb1uiEAU");
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "java3-ele";
        // 上传的文件的名称。
        String objectName = filename;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, defaultCredentialProvider);
        try {
            // 将文件传递给阿里的oss
            ossClient.putObject(bucketName, objectName, input);
            return "https://"+bucketName+".oss-cn-beijing.aliyuncs.com/"+filename;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
